package com.xvyy.tingshu.search.factory;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: ScheduledTaskThreadFactory
 * Package: com.xvyy.tingshu.search.factory
 *
 * @Description: 单例恶汉式模式创建定时任务线程池对象
 * @Author: xvyy
 * @Create: 2025/2/7 - 21:06
 * @Version: v1.0
 */
public class ScheduledTaskThreadFactory {

    // 1. 定义一个定时功能的线程池对象
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

    private static final ScheduledTaskThreadFactory INSTANCE = new ScheduledTaskThreadFactory();

    private ScheduledTaskThreadFactory() {
    }

    public static ScheduledTaskThreadFactory getInstance() {
        return INSTANCE;// 返回单例对象 多线程线程安全，恶汉式写法
        // return new ScheduledTaskThreadFactory(); // 多线程非线程安全，懒汉式写法
    }

    /**
     * 延时方式 + 线程池
     *
     * @param command
     * @param delay
     * @param timeUnit
     */
    public void executeTaskSchedule(Runnable command, long delay, TimeUnit timeUnit) {
        scheduledExecutorService.schedule(command, delay, timeUnit);
    }

    /**
     * 定时方式 + 线程池
     *
     * @param r
     * @param initialDelay
     * @param delay
     * @param unit
     */
    public void executeTaskScheduleWithFixedDelay(Runnable r, long initialDelay, long delay, TimeUnit unit) {
        scheduledExecutorService.scheduleWithFixedDelay(r, initialDelay, delay, unit);
    }

    /**
     * 计算当前时间和7天后的凌晨2点的时间差
     * @param currentTime
     * @return
     */
    public long timeDifference(Long currentTime) {
        LocalDate localDate = LocalDate.now().plusDays(7);// 7天后执行定时任务
        LocalDateTime localDateTime = LocalDateTime.of(localDate, LocalTime.of(2, 0, 0));// 凌晨2点执行定时任务
        long endTime = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        return Math.abs(currentTime - endTime);
    }
}
